<template>
  <div class="meeting-template-container">
    <div class="template-section">
      <h4>会务模板管理</h4>
      <p class="description">您可以下载标准模板并上传自定义模板文件</p>

      <div class="button-group">
        <!-- 下载模板按钮 -->
        <a-button
          type="primary"
          :loading="downloadLoading"
          @click="handleDownload"
        >
          <template #icon>
            <IconDownload />
          </template>
          下载模板
        </a-button>

        <!-- 上传模板按钮 -->
        <a-upload
          :custom-request="handleUpload"
          :show-file-list="false"
          accept=".xlsx,.xls,.docx,.doc,.pdf"
          @change="onUploadChange"
          @before-upload="onBeforeUpload"
        >
          <template #upload-button>
            <a-button
              type="outline"
              :loading="uploadLoading"
            >
              <template #icon>
                <IconUpload />
              </template>
              上传模板
            </a-button>
          </template>
        </a-upload>
      </div>

      <!-- 上传说明 -->
      <div class="upload-tips">
        <h5>上传说明：</h5>
        <ul>
          <li>支持的文件格式：Excel文件（.xlsx, .xls）、Word文档（.docx, .doc）、PDF文件（.pdf）</li>
          <li>文件大小不超过10MB</li>
          <li>请确保模板文件格式正确</li>
        </ul>
      </div>

      <!-- 最近操作记录 -->
      <div v-if="recentOperations.length > 0" class="recent-operations">
        <h5>最近操作：</h5>
        <div class="operation-list">
          <div
            v-for="(operation, index) in recentOperations"
            :key="index"
            class="operation-item"
          >
            <span class="operation-type" :class="operation.type">
              {{ operation.type === 'upload' ? '上传' : '下载' }}
            </span>
            <span class="operation-time">{{ operation.time }}</span>
            <span class="operation-status" :class="operation.status">
              {{ operation.status === 'success' ? '成功' : '失败' }}
            </span>
          </div>
        </div>
      </div>
    </div>
  </div>
</template>

<script setup>
import { defineEmits, reactive, ref } from 'vue'
import { Message } from '@arco-design/web-vue'
import { IconDownload, IconUpload } from '@arco-design/web-vue/es/icon'
import { downloadTemplate, uploadMeetingTemplate } from '@/apis/meet/template'

const emit = defineEmits(['template-uploaded'])

const downloadLoading = ref(false)
const uploadLoading = ref(false)
const recentOperations = reactive([])

/**
 * 添加操作记录
 */
const addOperation = (type, status) => {
  const operation = {
    type,
    status,
    time: new Date().toLocaleString()
  }
  recentOperations.unshift(operation)

  // 只保留最近5条记录
  if (recentOperations.length > 5) {
    recentOperations.splice(5)
  }
}

/**
 * 处理模板下载
 */
const handleDownload = async () => {
  downloadLoading.value = true
  try {
    const res = await downloadTemplate()
    if (res.success && res.data) {
      // 创建下载链接
      const link = document.createElement('a')
      link.href = res.data
      link.download = '会务模板.xlsx'
      document.body.appendChild(link)
      link.click()
      document.body.removeChild(link)

      Message.success('模板下载成功')

      // 记录操作
      addOperation('download', 'success')
    } else {
      Message.error(res.msg || '模板下载失败')
      addOperation('download', 'failed')
    }
  } catch (error) {
    console.error('下载模板失败:', error)
    Message.error('下载失败，请重试')
    addOperation('download', 'failed')
  } finally {
    downloadLoading.value = false
  }
}

/**
 * 处理模板上传
 */
const handleUpload = (options) => {
  // 直接用options.fileItem.file作为file
  const file = options.fileItem && options.fileItem.file
  const { onSuccess, onError } = options

  const uploadFile = async () => {
    // 文件类型验证
    const allowedTypes = [
      // Excel文件
      'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet', // .xlsx
      'application/vnd.ms-excel', // .xls
      // Word文档
      'application/vnd.openxmlformats-officedocument.wordprocessingml.document', // .docx
      'application/msword', // .doc
      // PDF文件
      'application/pdf' // .pdf
    ]

    const fileExtension = file.name.toLowerCase().split('.').pop()
    const allowedExtensions = ['xlsx', 'xls', 'docx', 'doc', 'pdf']

    if (!file || (!allowedTypes.includes(file.type) && !allowedExtensions.includes(fileExtension))) {
      Message.error('请上传Excel、Word或PDF文件（支持.xlsx、.xls、.docx、.doc、.pdf格式）')
      onError && onError(new Error('文件类型不支持'))
      return
    }

    // 文件大小验证（10MB）
    if (!file.size || file.size > 10 * 1024 * 1024) {
      Message.error('文件大小不能超过10MB')
      onError && onError(new Error('文件大小超限'))
      return
    }

    uploadLoading.value = true
    try {
      const formData = new FormData()
      formData.append('file', file)

      const res = await uploadMeetingTemplate(formData)
      if (res.success) {
        Message.success('模板上传成功')
        addOperation('upload', 'success')
        // 修正：上传成功后emit url，取res.data
        if (res.data) {
          emit('template-uploaded', res.data)
        }
        onSuccess && onSuccess(res)
      } else {
        Message.error(res.msg || '模板上传失败')
        addOperation('upload', 'failed')
        onError && onError(new Error(res.msg || '上传失败'))
      }
    } catch (error) {
      Message.error('上传失败，请重试')
      addOperation('upload', 'failed')
      onError && onError(error)
    } finally {
      uploadLoading.value = false
    }
  }

  uploadFile()

  return {
    abort() {
      // 如果需要，可以在这里实现取消上传的逻辑
    }
  }
}

/**
 * 上传状态变化处理
 */
const onUploadChange = (_fileList, _file) => {
  // 上传状态变化处理
}

/**
 * 上传前处理
 */
const onBeforeUpload = (_file) => {
  return true
}
</script>

<style scoped>
.meeting-template-container {
  padding: 20px;
}

.template-section h4 {
  margin-bottom: 8px;
  color: #1d2129;
}

.description {
  color: #86909c;
  margin-bottom: 24px;
  font-size: 14px;
}

.button-group {
  display: flex;
  gap: 16px;
  margin-bottom: 24px;
}

.upload-tips {
  background-color: #f7f8fa;
  padding: 16px;
  border-radius: 6px;
  margin-bottom: 24px;
}

.upload-tips h5 {
  margin-bottom: 8px;
  color: #1d2129;
  font-size: 14px;
}

.upload-tips ul {
  margin: 0;
  padding-left: 20px;
}

.upload-tips li {
  color: #86909c;
  font-size: 13px;
  line-height: 1.6;
}

.recent-operations h5 {
  margin-bottom: 12px;
  color: #1d2129;
  font-size: 14px;
}

.operation-list {
  display: flex;
  flex-direction: column;
  gap: 8px;
}

.operation-item {
  display: flex;
  align-items: center;
  gap: 12px;
  padding: 8px 12px;
  background-color: #f7f8fa;
  border-radius: 4px;
  font-size: 13px;
}

.operation-type {
  padding: 2px 8px;
  border-radius: 4px;
  font-size: 12px;
  font-weight: 500;
}

.operation-type.upload {
  background-color: #e8f4ff;
  color: #165dff;
}

.operation-type.download {
  background-color: #eff8ff;
  color: #0fc6c2;
}

.operation-time {
  color: #86909c;
  flex: 1;
}

.operation-status {
  font-weight: 500;
}

.operation-status.success {
  color: #00b42a;
}

.operation-status.failed {
  color: #f53f3f;
}
</style>
